package com.want.evenchat.controller.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;
import com.want.evenchat.R;
import com.want.evenchat.controller.activity.AddContactActivity;
import com.want.evenchat.controller.activity.ChatActivity;
import com.want.evenchat.controller.activity.GroupListActivity;
import com.want.evenchat.controller.activity.InviteActivity;
import com.want.evenchat.model.Model;
import com.want.evenchat.model.bean.UserInfo;
import com.want.evenchat.utils.Constant;
import com.want.evenchat.utils.SpUtils;

import java.security.acl.Group;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Want on 2018/5/4.
 */

public class ContactListFragment extends EaseContactListFragment{

    private ImageView imageview_contact_red;
    private LocalBroadcastManager mLBM;

    private BroadcastReceiver ContactInviteChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收这个广播后(更新红点显示)
            imageview_contact_red.setVisibility(View.VISIBLE);
            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE , true);

        }
    };
    private LinearLayout linearlayout;
    private BroadcastReceiver ContactChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新页面
            refreshContact();
        }
    };

    private String mHxid;

    private BroadcastReceiver GroupChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //显示红点
            imageview_contact_red.setVisibility(View.VISIBLE);

            SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE , true);
        }
    };


    //联系人页表页面

    @Override
    protected void initView() {
        super.initView();

        //布局显示加号
        titleBar.setRightImageResource(R.mipmap.em_add);

        //添加头布局
        View headView = View.inflate(getActivity(), R.layout.header_fragment_contact, null);
        listView.addHeaderView(headView);

        //获取红点对象
        imageview_contact_red = headView.findViewById(R.id.imageview_contact_red);

        //获取邀请信息条目的对象
        linearlayout = headView.findViewById(R.id.linearlayout_contact_invite);

        //listview条目的点击事件
        setContactListItemClickListener(new EaseContactListItemClickListener() {
            @Override
            public void onListItemClicked(EaseUser user) {

                if (user == null){
                    return;
                }

                Intent intent = new Intent(getActivity() , ChatActivity.class);
                intent.putExtra(EaseConstant.EXTRA_USER_ID , user.getUsername());
                startActivity(intent);
            }
        });

        //跳转群主列表页面
        LinearLayout linearlayout_contact_group = headView.findViewById(R.id.linearlayout_contact_group);
        linearlayout_contact_group.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), GroupListActivity.class);
                startActivity(intent);
            }
        });

    }

    @Override
    protected void setUpView() {
        super.setUpView();

        //添加按钮添加点击事件处理
        titleBar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity() , AddContactActivity.class));
            }
        });

        //初始化红点显示
        Boolean isNewInvite = SpUtils.getInstance().getBoolean(SpUtils.IS_NEW_INVITE, false);
        imageview_contact_red.setVisibility(isNewInvite? View.VISIBLE : View.GONE);

        //邀请信息条目的点击事件
        linearlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //隐藏红点(红点处理)
                imageview_contact_red.setVisibility(View.GONE);
                SpUtils.getInstance().save(SpUtils.IS_NEW_INVITE , false);

                //跳转到邀请信息列表页面
                startActivity(new Intent(getActivity() , InviteActivity.class));

            }
        });

        //注册广播
        mLBM = LocalBroadcastManager.getInstance(getActivity());
        mLBM.registerReceiver(ContactInviteChangeReceiver , new IntentFilter(Constant.CONTACT_INVITE_CHANGED));
        mLBM.registerReceiver(ContactChangeReceiver , new IntentFilter(Constant.CONTACT_CHANGED));
        mLBM.registerReceiver(GroupChangeReceiver , new IntentFilter(Constant.GROUP_INVITE_CHANGED));


        //从环信服务器获取所有联系人信息
        getContactFromHxServer();

        //绑定listview和contextmenu
        registerForContextMenu(listView);

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        //获取环信id
        int position = ((AdapterView.AdapterContextMenuInfo) menuInfo).position;

        EaseUser easeUser = (EaseUser) listView.getItemAtPosition(position);

        mHxid = easeUser.getUsername();

        //添加布局
        getActivity().getMenuInflater().inflate(R.menu.delete, menu);
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.contact_delete){
            //调用执行删除选中的联系人操作
            deleteContact();

            return true;
        }

        return super.onContextItemSelected(item);
    }

    //执行删除选中的联系人操作的方法
    private void deleteContact() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //从环信服务器中删除联系人
                    EMClient.getInstance().contactManager().deleteContact(mHxid);

                    //本地数据库更新
                    Model.getInstance().getDBManager().getContactTableDAO().deleteContactByHxId(mHxid);

                    if (getActivity() == null){
                        return;
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            //内存变化(刷新页面)


                            //Toast提示
                            Toast.makeText(getActivity(), "该联系人已删除", Toast.LENGTH_SHORT).show();

                            refreshContact();

                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                    if (getActivity() == null){
                        return;
                    }

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "删除好友失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    //从环信服务器获取所有联系人信息
    private void getContactFromHxServer() {
        Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取到所有的好友的环信ID
                    List<String> hxids = EMClient.getInstance().contactManager().getAllContactsFromServer();

                    //先进行校验
                    if (hxids != null && hxids.size() >= 0){

                        List<UserInfo> contacts = new ArrayList<UserInfo>();

                        //转换
                        for (String hxid : hxids){
                            UserInfo userInfo = new UserInfo(hxid);

                            contacts.add(userInfo);
                        }

                        //保存好友信息到本地数据库
                        Model.getInstance().getDBManager().getContactTableDAO().saveContacts(contacts , true);

                        if (getActivity() == null){
                            return;
                        }

                        //刷新页面
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //刷新页面的方法
                                refreshContact();
                            }
                        });
                    }

                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void refreshContact() {
        //刷新页面  获取数据
        List<UserInfo> contacts = Model.getInstance().getDBManager().getContactTableDAO().getContacts();

        //校验
        if (contacts != null && contacts.size() >= 0){
            //设置数据
            Map<String, EaseUser> contactsMap = new HashMap<>();

            //转换
            for (UserInfo contact : contacts){
                EaseUser easeUser = new EaseUser(contact.getHxid());

                contactsMap.put(contact.getHxid() , easeUser);
            }

            setContactsMap(contactsMap);

            //刷新页面
            refresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //关闭广播
        mLBM.unregisterReceiver(ContactInviteChangeReceiver);

        mLBM.unregisterReceiver(ContactChangeReceiver);

        mLBM.unregisterReceiver(GroupChangeReceiver);

    }
}
